const mysql = require("mysql")

const { toHump } = require("../utils/index")

const { host, user, password, database } = require("../config/config")

const pool = mysql.createPool({
  host,
  user,
  password,
  database
})

// module.exports.query = (sql, value, callback) => {
// 	pool.getConnection((err, connection) => {
// 		if (err) {
// 			console.log('数据库连接失败')
// 			pool.releaseConnection() //释放链接
// 			let error = {
// 				code: '500',
// 				msg: '数据库连接失败'
// 			}
// 			callback(error)
// 		} else {
// 			connection.query(sql, value, (err, row) => {
// 				if (err) {
// 					console.log('sql语句执行失败，没有找到指定的结果')
// 					connection.release() //释放链接
// 					let error = {
// 						code: '500',
// 						msg: 'Sql语句执行失败，没有找到指定的结果'
// 					}
// 					callback(error)
// 				} else {
// 					connection.release()
// 					if (row instanceof Array) {
// 						let response = {
// 							code: '200',
//               msg:'',
// 							data: toHump(row)
// 						}
// 						callback(response)
// 					} else {
// 						let response = {
// 							code: '200',
//               msg:'',
// 							data: []
// 						}
// 						callback(response)
// 					}
// 				}
// 			})
// 		}
// 	})
// }

module.exports.query = (sql, params=[]) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, conn) => {
      if (err) {
        let error = {
          code: 500,
          msg: "Sql语句执行失败",
					data:null,
          err:err
        }
        reject(error)
      } else {
        conn.query(sql, params, (error, results) => {
          let response = {}
          conn.release() //释放连接池中的连接
          if (error) {
            reject(error)
          } else {
            if (results instanceof Array) {
              response = {
                code: 200,
                msg: "ok",
                data: toHump(results)
              }
            } else {
              response = {
                code: 200,
                msg: "ok",
                data: []
              }
            }
            resolve(response)
          }
        })
      }
    })
  })
}
